//
//  HomePageListView.m
//  HYApp
//
//  Created by Jianbo Cai on 2020/7/28.
//  Copyright © 2020 Unidax. All rights reserved.
//

#import "HomePageListView.h"
#import "OverviewTableViewCell.h"
#import "DigitalTableViewCell.h"
#import "CurrenciesTableViewCell.h"
#import "AccountMainViewController.h"
#import "DigitalTransferViewController.h"
#import "DigitalWithdrawViewController.h"
#import "DigitalExchangeViewController.h"
#import "DigitalDepositViewController.h"

@interface HomePageListView ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, copy) void(^scrollCallback)(UIScrollView *scrollView);

@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UILabel *assetLabel;

@property (nonatomic, assign) NSInteger type;
@property (nonatomic, strong) NSMutableSet *selectSet;

@end

@implementation HomePageListView

- (instancetype)initWithFrame:(CGRect)frame type:(NSInteger)type
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        self.type = type;
        
        _tableView = [[UITableView alloc] initWithFrame:frame style:UITableViewStylePlain];
        self.tableView.backgroundColor = self.backgroundColor;
        self.tableView.tableFooterView = [[UIView alloc]init];
        self.tableView.dataSource = self;
        self.tableView.delegate = self;
        self.tableView.separatorColor = AWThemeColorForKey(@"Market.ipoTopLinecolor");
        self.tableView.separatorInset = UIEdgeInsetsZero;
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self addSubview:self.tableView];
    
        if (self.type == 0) {
            [self.tableView registerNib:[UINib nibWithNibName:@"OverviewTableViewCell" bundle:nil] forCellReuseIdentifier:@"OverviewTableViewCell"];
            OverviewTableViewCell *cell = [[[NSBundle mainBundle] loadNibNamed:@"OverviewTableViewCell" owner:nil options:nil] firstObject];
            cell.backgroundColor = [UIColor whiteColor];
            cell.leftLabel.text = JFMainLocalizedString(@"Asset Class");
            cell.rightLabel.text = JFMainLocalizedString(@"NAV(USD)");
            cell.leftLabel.textColor = cell.rightLabel.textColor = UIColorFromHex(0x565656);
            self.tableView.tableHeaderView = cell;
        }else if (self.type == 1) {
            [self.tableView registerNib:[UINib nibWithNibName:@"DigitalTableViewCell" bundle:nil] forCellReuseIdentifier:@"DigitalTableViewCell"];
            self.tableView.tableHeaderView = self.headerView;
        }else if (self.type == 2) {
            [self.tableView registerNib:[UINib nibWithNibName:@"CurrenciesTableViewCell" bundle:nil] forCellReuseIdentifier:@"CurrenciesTableViewCell"];
            self.tableView.tableHeaderView = self.headerView;
        }
    }
    return self;
}

- (void)displaySection:(UITapGestureRecognizer *)tapGesture {
    NSInteger index = tapGesture.view.tag - 1000;
    if ([self.selectSet containsObject:@(index)]) {
        [self.selectSet removeObject:@(index)];
    }else {
        [self.selectSet addObject:@(index)];
    }
    [self.tableView reloadData];
}

- (void)setWalletsEntity:(WalletsEntity *)walletsEntity {
    _walletsEntity = walletsEntity;
    
    
    if (self.type == 1) {
        // 排序
        if (Currencies().currencieList.count) {
            self.walletsEntity.digital.balance = [self.walletsEntity.digital.balance sortedArrayUsingComparator:^NSComparisonResult(BalanceListEntity *  _Nonnull obj1, BalanceListEntity *  _Nonnull obj2) {
                return [Currencies().symbolSortArray indexOfObject:obj1.asset_symbol] > [Currencies().symbolSortArray indexOfObject:obj2.asset_symbol];
            }];
        }
        self.assetLabel.text = MoneyFormat(walletsEntity.digital.usdTotalValue);
    }else if (self.type == 2) {
        NSString *total = @(self.walletsEntity.hkAccount.usdTotalValue.doubleValue + self.walletsEntity.usAccount.usdTotalValue.doubleValue + self.walletsEntity.sgAccount.usdTotalValue.doubleValue).stringValue;
        self.assetLabel.text = MoneyFormat(total);
    }
    [self.tableView reloadData];
}


#pragma mark - UITableViewDataSource, UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    switch (self.type) {
        case 0:
            return 6;
            break;
        case 1:
            return self.walletsEntity.digital.balance.count;
            break;
        default:
            return 3;
            break;
    }
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (self.type) {
        case 0:
            return (section == 0) ? 3 : 0;
            break;
        case 1:
            return 1;
            break;
        default:
            return 1;
            break;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.type == 0) {
        OverviewTableViewCell *cell =  [tableView dequeueReusableCellWithIdentifier:@"OverviewTableViewCell" forIndexPath:indexPath];
        cell.leftLabel.text = @[JFMainLocalizedString(@"hkAccount"), JFMainLocalizedString(@"usAccount"), JFMainLocalizedString(@"sgAccount")][indexPath.row];
        switch (indexPath.row) {
            case 0:
                cell.rightLabel.text = MoneyFormat(self.walletsEntity.hkAccount.usdTotalValue);
                break;
            case 1:
                cell.rightLabel.text = MoneyFormat(self.walletsEntity.usAccount.usdTotalValue);
                break;
            case 2:
                cell.rightLabel.text = MoneyFormat(self.walletsEntity.sgAccount.usdTotalValue);
                break;
            default:
                break;
        }


        cell.rightLabel.font = cell.leftLabel.font = [UIFont fontWithName:@"PingFang SC" size: 15];
        cell.leftLabel.textColor = cell.rightLabel.textColor = UIColorFromHex(0x565656);
        cell.lineView.hidden = (indexPath.row != 2);
        cell.leftLeadingLayout.constant = 40;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else if (self.type == 1) {
        DigitalTableViewCell *cell =  [tableView dequeueReusableCellWithIdentifier:@"DigitalTableViewCell" forIndexPath:indexPath];
        BalanceListEntity *entity = self.walletsEntity.digital.balance[indexPath.section];
        cell.entity = entity;
        WEAKSELF
        cell.action = ^(FunctionActionType type) {
            switch (type) {
                case FunctionActionTypeDeposit: {
                    DigitalDepositViewController *vc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil]instantiateViewControllerWithIdentifier:@"DigitalDepositViewController"];
                    if ([entity.asset_address isEqualToString:@"BTC"]) {
                        vc.public_address = weakSelf.walletsEntity.digital.public_address_btc;
                    }else {
                        vc.public_address = weakSelf.walletsEntity.digital.public_address;
                    }
                    vc.asset_address = entity.asset_address;
                    [weakSelf.viewController.navigationController pushViewController:vc animated:YES];
                }
                    break;
                case FunctionActionTypeExchange: {
                    DigitalExchangeViewController *vc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil]instantiateViewControllerWithIdentifier:@"DigitalExchangeViewController"];
                    vc.walletsId = self.walletsEntity.digital.wallet_id;
                    vc.asset_address = entity.asset_address;
                    [weakSelf.viewController.navigationController pushViewController:vc animated:YES];
                }
                    break;
                case FunctionActionTypeTransfer: {
                    DigitalTransferViewController *vc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil]instantiateViewControllerWithIdentifier:@"DigitalTransferViewController"];
                    vc.fromBalance = entity;
                    vc.walletsEntity = self.walletsEntity;
                    [weakSelf.viewController.navigationController pushViewController:vc animated:YES];
                }
                    break;
                case FunctionActionTypeWithdraw: {
                    DigitalWithdrawViewController *vc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil]instantiateViewControllerWithIdentifier:@"DigitalWithdrawViewController"];
                    vc.balance = entity;
                    vc.wallet_id = self.walletsEntity.digital.wallet_id;
                    [weakSelf.viewController.navigationController pushViewController:vc animated:YES];
                }
                    break;
                default:
                    break;
            }
        };
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else if (self.type == 2) {
        CurrenciesTableViewCell *cell =  [tableView dequeueReusableCellWithIdentifier:@"CurrenciesTableViewCell" forIndexPath:indexPath];
        [cell.image setImage:[UIImage imageNamed:@[@"HKD", @"USD", @"SGD"][indexPath.section]]];
        cell.account.text = @[JFMainLocalizedString(@"hkAccount"), JFMainLocalizedString(@"usAccount"), JFMainLocalizedString(@"sgAccount")][indexPath.section];
        switch (indexPath.section) {
            case 0:
                cell.accountVaule.text = [NSString stringWithFormat:@"$ %@", MoneyFormat(self.walletsEntity.hkAccount.usdTotalValue)];
                break;
            case 1:
                cell.accountVaule.text = [NSString stringWithFormat:@"$ %@", MoneyFormat(self.walletsEntity.usAccount.usdTotalValue)];
                break;
            case 2:
                cell.accountVaule.text = [NSString stringWithFormat:@"$ %@", MoneyFormat(self.walletsEntity.sgAccount.usdTotalValue)];
                break;
            default:
                break;
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (self.type) {
        case 0:
            return 44;
            break;
        case 1:
        {
            if ([self.selectSet containsObject:@(indexPath.section)]) {
                return 130;
            }else {
                return 80;
            }
        }
            break;
        default:
            return 80;
            break;
    }
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (self.type == 0) {
        OverviewTableViewCell *cell = [[[NSBundle mainBundle] loadNibNamed:@"OverviewTableViewCell" owner:nil options:nil] firstObject];
        cell.frame = CGRectMake(0, 0, SCREEN_WIDTH, 44);
        cell.backgroundColor = [UIColor whiteColor];
        cell.leftLabel.text =  @[JFMainLocalizedString(@"currencies"), JFMainLocalizedString(@"insurance"), JFMainLocalizedString(@"digital"), JFMainLocalizedString(@"securities"), JFMainLocalizedString(@"commodities"), JFMainLocalizedString(@"alternatives")][section];
        if (section == 0) {
            NSString *total = @(self.walletsEntity.hkAccount.usdTotalValue.doubleValue + self.walletsEntity.usAccount.usdTotalValue.doubleValue + self.walletsEntity.sgAccount.usdTotalValue.doubleValue).stringValue;
            cell.rightLabel.text = MoneyFormat(total);
        }else if (section == 2){
            cell.rightLabel.text = MoneyFormat(self.walletsEntity.digital.usdTotalValue);
        }else
            cell.rightLabel.text = @"0.00";
//        cell.rightLabel.text = @[@"1000", @"1200", @"9,000", @"9,300", @"2000", @"520"][section];
        cell.leftLabel.textColor = cell.rightLabel.textColor = UIColorFromHex(0x708A6A);
        cell.tag = 1000 + section;
        cell.AWaddTapGestureRecognizer(self, @selector(displaySection:));
        cell.lineView.hidden = (section == 0);
        return cell;
    }else if (self.type == 1) {
        
    }
    
    return [[UIView alloc]init];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    switch (self.type) {
        case 0:
            return 44;
            break;
        case 1:
        {
            
        }
            break;
        default:
            break;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    switch (self.type) {
        case 0:
            return 0;
            break;
        case 1:
            return 15;
            break;
        case 2:
            return 15;
            break;
        default:
            break;
    }
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc]init];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (self.type) {
        case 0:
            
            break;
        case 1:
        {
            if ([self.selectSet containsObject:@(indexPath.section)]) {
                [self.selectSet removeObject:@(indexPath.section)];
            }else {
                [self.selectSet addObject:@(indexPath.section)];
            }
            [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        }
            break;
        case 2:
        {
            AccountMainViewController *vc = [[AccountMainViewController alloc]init];
            vc.walletsEntity = self.walletsEntity;
            vc.selectIndex = indexPath.section;
            [self.viewController.navigationController pushViewController:vc animated:YES];
        }
            break;
        default:
            break;
    }
}

#pragma mark - JXPagingViewListViewDelegate
- (UIScrollView *)listScrollView {
    return self.tableView;
}

- (void)listViewDidScrollCallback:(void (^)(UIScrollView *))callback {
    self.scrollCallback = callback;
}

- (UIView *)listView {
    return self;
}

- (void)listDidAppear {

}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (self.scrollCallback) {
        self.scrollCallback(scrollView);
    }
}


- (NSMutableSet *)selectSet {
    if (!_selectSet) {
        _selectSet = [NSMutableSet setWithCapacity:5];
    }
    return _selectSet;
}

- (UIView *)headerView {
    if (!_headerView) {
        _headerView =  [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 105)];
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(12,15,SCREEN_WIDTH,16)];
        label.text = (self.type == 1) ? JFMainLocalizedString(@"Digital Asset Value") : JFMainLocalizedString(@"Currencies Asset Value");
        label.font = [UIFont fontWithName:@"PingFangSC-Medium" size:15];
        label.textColor = UIColorFromHex(0x565656);
        [_headerView  addSubview:label];
        
        self.assetLabel = [[UILabel alloc]initWithFrame:CGRectMake(12,40,SCREEN_WIDTH,30)];
        self.assetLabel.text = @"$ --";
        self.assetLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:30];
        self.assetLabel.textColor = UIColorFromHex(0x343434);
        [_headerView  addSubview:self.assetLabel];
        
        UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, 84.5, SCREEN_HEIGHT, 0.5)];
        line.backgroundColor = UIColorFromHex(0xE5E5E5);
        [_headerView addSubview:line];
    }
    return _headerView;
}


@end
